package ru.papergames.model
{
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;

	
	/**
	 * Handles Objects with quantity field
	 * If quantity=0 - object shall be removed from here!
	 * Grouping by 'key' property
	 * 
	 * */
	public class ItemsArrayCollection extends ArrayCollection
	{
		
		private var listSort:Sort = new Sort();
		
		public function ItemsArrayCollection(source:Array=null)
		{
			super(source);
			this.addEventListener(CollectionEvent.COLLECTION_CHANGE, onCollectionChange);
			
			//init sorting
			listSort.fields = [ new SortField('title', true) ];
			sort = listSort;
			
			refresh();
		}
		
		private function onCollectionChange(evt:CollectionEvent):void {
			if (evt.kind == CollectionEventKind.UPDATE) {
				var indexesToRemove:Array = [];
				
				for (var i:uint=0; i < source.length; i++) {
					if (list.getItemAt(i).quantity <= 0) indexesToRemove.unshift(i);
				}				
				
				for each (var index:uint in indexesToRemove) 
					list.removeItemAt(index);
						
			}
		}
		
		public function getItemByKey(key:String):Object {

			for each (var item:Object in source) {
				if (item.key == key)
					return item;
			}
			
			
			return null;
		}
		
		override public function addItemAt(item:Object, index:int):void {
			if (item.quantity) {
				//grouping
				var sameItem:Object = getItemByKey( item.key );
				if (sameItem) {
					sameItem.quantity += item.quantity;
					this.refresh();
				} else {
					super.addItemAt(item, index);
				}
			}
		}
		
		override public function removeAll():void {
			list.removeAll();
			this.source.length = 0;
		}
		
	}
}